/**
 * 
 */
package org.shark.jdbcTemplateTool.utils.sql;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.shark.jdbcTemplateTool.exception.SqlFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lenovo
 * @description
 * @date 2016年8月15日
 */
public class SqlFileUtil extends AbstractBaseSqlLoad implements SqlLoad {

	private static final String FILE_EXT = ".sql";

	private static final Logger log = LoggerFactory.getLogger(SqlFileUtil.class);
	
	public static SqlFileUtil newInstance = new SqlFileUtil();

    /**
     * 初始化加载sql语句到map
     * @throws SqlFormatException 
     */
    public synchronized void init(boolean isInit, String cacheName) throws SqlFormatException {
    	
    	List<File> files = scanFiles(cacheName);
        
        String fileName = null;
        String filePath = null;
        BufferedReader reader = null;
        StringBuffer sb = null;
        try {
            for (File sqlfile : files) {
            	
            	sb = new StringBuffer();
            	
                fileName = sqlfile.getName();
                filePath = sqlfile.getPath();
                
                String key = getFileKey(filePath, classRootPath);
                if(isInit && containsKey(key)){
                	throw new SqlFormatException("sql文件" + fileName + "的" + key + "的存在重复命名");
                } else if(containsKey(key)){
                	throw new SqlFormatException("sql文件" + fileName + "的" + key + "的存在重复命名");
                }
                
                // 讀取文件内容
                reader = new BufferedReader(new FileReader(sqlfile));
                String tempString = "";
                while ((tempString = reader.readLine()) != null) {
                	sb.append(tempString);
                }
                reader.close();
                
                String sql = sb.toString();
                if(null == sql || sql.trim().isEmpty()){
                	throw new SqlFormatException("sql文件" + fileName + "的存在没有内容的sql语句");
                }
                sql = sql.replaceAll("[\\s]{2,}", " ");
                putCache(key, sql);
                log.info("sql加载, sql file = " + fileName + ", sql key = " + key + ", sql content = " + sql);
                
            }
        } catch (IOException e) {
        	throw new SqlFormatException("sql文件" + fileName + "读取异常", e);
        }
    }
    
    private String getFileKey(String filePath, String rootPath) {
    	String tmpRootPath = rootPath.substring(1).replace("\\", "/");
    	String packageName = filePath.replace("\\", "/").replace(tmpRootPath, "").replace("/", ".");
    	packageName = packageName.replace(FILE_EXT, "").replace("_", ".");
    	return packageName;
    }
    
    protected String getFileExt() {
    	return FILE_EXT;
    }
    
}
